<template>
  <el-dialog :title="'办卡'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="auto">
      <!--      <el-form-item label="搜索会员" prop="memberId" v-if="!readonly">
        <el-select style="width:100%;" v-model="dataForm.memberId" filterable remote reserve-keyword @change="selectMember"
          placeholder="请输入姓名/电话" :remote-method="remoteMethod" :loading="loading">
          <el-option v-for="item in platfromMembers" :key="item.id" :label="'[昵称]'+item.name+' --- [姓名]'+ ( item.zsName == null ? '暂未设置':item.zsName )+' --- [手机]'+item.tel"
            :value="item.id"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="手机" prop="mobile">
        <el-input v-model="dataForm.mobile" maxlength="11" @change="changgephone" placeholder="手机"></el-input>
      </el-form-item>
      <el-form-item label="会员编号" prop="cardNo">
        <el-input :readonly="true" v-model="dataForm.cardNo" placeholder="会员编号"></el-input>
      </el-form-item>
      <el-form-item label="会员卡号">
        <el-input v-model="dataForm.cardJustNo" placeholder="会员卡号"></el-input>
      </el-form-item>
      <el-form-item label="卡内码">
        <el-input v-model="dataForm.cardInpNo" placeholder="卡内码"></el-input>
      </el-form-item>
      <el-form-item label="等级类型" prop="levelId">
        <el-select style="width:100%;" v-model="dataForm.levelId" placeholder="请选择等级" @change="updatePayAcount">
          <el-option v-for="item in levelList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="会员费" prop="payAmount">
        <el-input v-model="dataForm.payAmount" @change="inputChange" placeholder="会员费"></el-input>
      </el-form-item>
      <el-form-item label="付款类型" prop="payState">
        <el-radio-group v-model="payState">
          <el-radio :label="0">现付</el-radio>
          <el-radio :label="1">转房账</el-radio>
        </el-radio-group>

        <el-select v-if="dataForm.payState == 1" v-model="dataForm.accPeoId" prop="accPeoId" filterable remote
          reserve-keyword placeholder="请输入关键词" :remote-method="accPeoRemoteMethod" :loading="remoteMethodLoading">
          <el-option v-for="item in accPeoOptions" :key="item.id" :label="item.roomSign +item.roomNum +  ' ' + item.name + (item.state == 1 ? '在住':'未结')"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item size="small" label="付款方式" prop="payType" v-show="dataForm.payState == 0">
        <el-select @change="payStateChange" v-model="dataForm.payType" placeholder="请选择">
          <el-option v-for="item in options.paysTypeOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <!--    <el-form-item label="付款方式" prop="payType" v-if="dataForm.payState == 0">
        <el-radio label="0" v-model="dataForm.payType" name="payType" >现金</el-radio>
        <el-radio label="1"  v-model="dataForm.payType" name="payType" >微信</el-radio>
        <el-radio label="2"  v-model="dataForm.payType" name="payType" >支付宝</el-radio>
        <el-radio label="3"  v-model="dataForm.payType" name="payType" >银行卡</el-radio>
        <el-radio label="4"  v-model="dataForm.payType" name="payType" >其他</el-radio>
      </el-form-item> -->
      <el-form-item label="姓名" prop="name">
        <el-input v-model="dataForm.name" placeholder="姓名" style="width: 195px;"></el-input>
        <el-button size="small" class="in_block" style="margin-left: 20px;" @click="readIdCard(peopleIndex)">读取身份证</el-button>
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-radio-group v-model="gender">
          <el-radio :label="1">男</el-radio>
          <el-radio :label="2">女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="证件类型" prop="certificate">
        <el-select v-model="dataForm.certificate" placeholder="请选择" >
          <el-option v-for="item in documentTypelist" :key="item.id" :label="item.label" :value="item.id"  >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="证件号" prop="certificateNo">
        <el-input v-model="dataForm.certificateNo" placeholder="证件号"></el-input>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="dataForm.address" placeholder="地址"></el-input>
      </el-form-item>

      <el-form-item label="消费密码" prop="password">
        <el-input v-if="payPwd" v-model="dataForm.password" :placeholder="payPwd" show-password></el-input>
        <el-input v-if="!payPwd" v-model="dataForm.password" placeholder="消费密码" show-password></el-input>
      </el-form-item>
      <el-form-item label="有效期" prop="endTimeType">
        <el-radio-group v-model="endTimeType">
          <el-radio :label="false">无限制</el-radio>
          <el-radio :label="true">截至到</el-radio>
        </el-radio-group>

        <el-date-picker v-model="dataForm.endTime" type="date" value-format="yyyy/MM/dd" placeholder="选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="推荐员工" prop="salesman">
        <el-input v-model="dataForm.salesman" placeholder="推荐员工"></el-input>
      </el-form-item>

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">{{ $t('Common.Cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmit()">{{ $t('Common.Confirm') }}</el-button>
    </span>


    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" title="请扫描二维码" :visible.sync="payVisible"
      width="30%" append-to-body>
      <div v-loading="payLoding" element-loading-text="正在执行支付">
        <div style="  display: flex;
      justify-content: center;
      align-items: center;margin-bottom:10px">
          <img src="../../../../assets/img/barCode.jpg" />
        </div>

        <div style="text-align:center">支持微信或支付宝条码支付</div>
        <div style="text-align:center">请用条码枪进行扫描</div>
        <span>
          <el-input v-model="auth_no" placeholder="请扫描二维码,支持微信支付宝" @keyup.enter.native="authClose" ref="inputFocus"></el-input>
        </span>
      </div>
    </el-dialog>


  </el-dialog>
</template>

<script>
  export default {
    data() {
      return {
        payState: 0,
        gender: 1,
        endTimeType: false,
        options: { //支付选项
          paysTypeOptions: [],
          peopleOptions: []
        },
        documentTypelist: [],
        readonly: false,
        platformMember: {},
        visible: false,
        levelList: [],
        accPeoOptions: [],
        sellerId: 0,
        //
        platfromMembers: [],
        value: "",
        list: [],
        remoteMethodLoading: false,
        loading: false,
        states: [],
        payPwd: null,
        //
        dataForm: {
          id: 0,
          payState: 0,
          payAmount: '',
          endTimeType: false,
          cardInpNo: "",
          levelId: "",
          accPeoId: "",
          cardJustNo: "",
          memberId: "",
          certificate: "",
          certificateNo: "",
          password: "",
          name: "",
          mobile: "",
          gender: 1,
          payType: "0",
          cardNo: "",
          address: "",
          creator: "",
          createDate: "",
          updateDate: "",
          sellerId: "",
          status: "",
          salesman: "",
          score: "",
          balance: "",
          zjlx:""
        },
        timer: null,
        payInterfaceConfig: {}, //支付
        payVisible: false,
        payLoding: false,
        payTypeSign: false,
        auth_no: '',
        istrues: 0,
        dataRule: {
          endTimeType: [{
            required: true,
            message: "有效期不能为空",
            trigger: "blur"
          }],
          payType: [{
            required: true,
            message: "支付类型不能为空",
            trigger: "blur"
          }],
          accPeoId: [{
            required: true,
            message: "转账人不可为空",
            trigger: "blur"
          }],
          payState: [{
            required: true,
            message: "付款类型不能为空",
            trigger: "blur"
          }],
          levelId: [{
            required: true,
            message: "等级类型不能为空",
            trigger: "blur"
          }],
          memberId: [{
            required: true,
            message: "会员ID不能为空",
            trigger: "blur"
          }],
          certificate: [{
            required: true,
            message: "证件类型不能为空",
            trigger: "blur"
          }],
          certificateNo: [{
            required: true,
            message: "证件号不能为空",
            trigger: "blur"
          }],
          name: [{
            required: true,
            message: "名字不能为空",
            trigger: "blur"
          }],
          mobile: [{
            required: true,
            message: "手机不能为空",
            trigger: "blur"
          }],
          gender: [{
            required: true,
            message: "性别不能为空",
            trigger: "blur"
          }],
          address: [{
            required: true,
            message: "联系地址不能为空",
            trigger: "blur"
          }],
          creator: [{
            required: true,
            message: "创建者不能为空",
            trigger: "blur"
          }],
          createDate: [{
            required: true,
            message: "创建时间不能为空",
            trigger: "blur"
          }],
          updateDate: [{
            required: true,
            message: "修改时间不能为空",
            trigger: "blur"
          }],
          sellerId: [{
            required: true,
            message: "商家ID不能为空",
            trigger: "blur"
          }],
          status: [{
            required: true,
            message: "状态，1为有效不能为空",
            trigger: "blur"
          }],
          salesman: [{
            required: false,
            message: "推荐员工不能为空",
            trigger: "blur"
          }],
          score: [{
            required: true,
            message: "积分不能为空",
            trigger: "blur"
          }],
          balance: [{
            required: true,
            message: "余额不能为空",
            trigger: "blur"
          }]
        }
      };
    },
    methods: {
      inputChange(val) {
        this.dataForm.payAmount = val
        this.$forceUpdate()
      },
      getPayInterface() {
        this.$http({
          url: this.$http.adornUrl(`/hotel/thotelsellerpayinterfaceconfig/myInfo`),
          method: 'get'
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.payInterfaceConfig = data.tHotelSellerPayInterfaceConfig
          } else {
            this.$message.error("加载支付配置失败")
          }
        })
      },
      payStateChange(val) {
        console.log(val)
        this.dataForm.payType = val
        this.$forceUpdate()
      },
      //获取支付方式
      getPayTypes() {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelfloorroompaytype/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: 1,
            limit: 999,
            isDeposit: 1,
            state: 1
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.options.paysTypeOptions = data.page.list;
            if (this.options.paysTypeOptions.length > 0) {
              this.dataForm.payType = this.options.paysTypeOptions[0].id
            }
            // this.dataForm.payType = this.options.paysTypeOptions[0].id;
          } else {
            this.options.paysTypeOptions = [];
          }
        });
      },
      changeFocus() {
        this.$nextTick(() => {
          this.$refs.inputFocus.focus();
        })
      },
      readIdCard(index) {
        var CardEntity = {
          Name: "张三",
          Sex: "男"
        };
        var postData = {
          DeviceType: "IDCardHareware",
          Params: JSON.stringify(CardEntity)
        };
        this.Post(postData, "Read", index);
      },
      Post(postData, methods, index) {
        this.istrues = 0;
        this.axios({
          url: this.axios.postUrl(`/api/Service/` + methods),
          method: 'POST',
          data: postData,
          cache: false,
          async: false,
          contentType: "application/json"
        }).then(({
          data
        }) => {
          this.istrues = 1;
          if (data.isSuccess == true) {
            this.dataForm.name = data.Name;
            if (data.Sex == "男") {
              this.dataForm.gender = "1"
            } else {
              this.dataForm.gender = "2"
            }
            this.dataForm.certificateNo = data.IDCardNumber
            this.dataForm.address = data.Address;
            this.dataForm.certificate = "0";
          } else {
            this.$message({
              message: data.message,
              type: "error",
              duration: 1500
            });
          }
        })
      },
      isputile(istrues, that) {
        setTimeout(function() {
          if (istrues == 0) {
            that.$message({
              message: "接口程序未打开，请打开接口程序",
              type: "error",
              duration: 1500
            });
          }
        }, 2000);
      },
      changgephone() {
        //远程查询
        this.$http({
          url: this.$http.adornUrl("/hotel/thotelmemberlabel/changgephone"),
          params: this.$http.adornParams({
            page: 1,
            limit: 999,
            key: this.dataForm.mobile
          }),
          method: "GET"
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {

            if (data.page.name != null) {
              this.dataForm = data.page;
            } else {
              var a = this.dataForm.mobile;
              this.dataForm = {};
              this.dataForm.mobile = a;
            }
            console.log(this.dataForm)
          }
        });
      },
      accPeoRemoteMethod(query) {
        if (query !== '') {
          this.remoteMethodLoading = true;
          //远程查询
          this.$http({
            url: this.$http.adornUrl("/hotel/thotelfloorroomcheckinpeople/list"),
            params: this.$http.adornParams({
              page: 1,
              limit: 999,
              key: query
            }),
            method: "GET"
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              console.log(data.page);
              this.accPeoOptions = data.page.list;
            } else {
              this.accPeoOptions = [];
            }
            this.remoteMethodLoading = false;
          });
        } else {
          this.accPeoOptions = [];
        }
      },
      loadSellerLevel(sellerId) {
        return this.$http({
          url: this.$http.adornUrl("/hotel/hotelmemberlevel/sellerLevleList"),
          params: this.$http.adornParams({
            sellerId
          }),
          method: "GET"
        }).then(({
          data
        }) => {
          this.levelList = data.data;
          return this.levelList;
        });
      },
      async updatePayAcount() {
        const level = await this.levelList.find(l => l.id == this.dataForm.levelId);
        this.dataForm.payAmount = level.payAmount;
        this.dataForm.cardRealMoney = level.payAmount;
      },
      selectMember(id) {
        console.log(this.platfromMembers)
        const member = this.platfromMembers.find(m => m.id === id)
        this.dataForm.mobile = member.tel;
        this.dataForm.certificateNo = member.identityNo;
        this.dataForm.name = member.zsName;
        this.dataForm.gender = member.gender;
        this.payPwd = member.payPwd ? "******" : null;
      },
      getagreementType(type) {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelagreementtype/list'),
          method: 'get',
          params: this.$http.adornParams({
            page: 1,
            limit: 999,
            type: type
          })
        }).then(({
          data
        }) => {
          this.documentTypelist = data.page.list;
          if (!this.dataForm.id && this.documentTypelist.length > 0) {
            this.dataForm.certificate = this.documentTypelist[0].id
          }
        });
      },
      init(platformMember) {
        this.options = { //支付选项
            paysTypeOptions: [],
            peopleOptions: []
          };
        this.getagreementType('document_type');
        this.remoteMethod();
        this.getPayInterface();
        this.getPayTypes();
        this.loadSellerLevel();
        this.visible = true;
        this.payPwd = null;
        this.readonly = false;
        this.dataForm = {}
        if (platformMember != undefined) {
          this.dataForm = platformMember;
        }
        this.$nextTick(() => {
          if (this.dataForm != null && this.dataForm.id != null) {
            this.$http({
              url: this.$http.adornUrl(
                `/hotel/hotelmemberleveldetail/info/${this.dataForm.id}`
              ),
              method: "get",
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                data.hotelMemberLevelDetail.endTimeType = data.hotelMemberLevelDetail.endTimeType + "";
                data.hotelMemberLevelDetail.payAmount = 0;
                this.dataForm = data.hotelMemberLevelDetail;
                this.readonly = true;
                if (data.hotelMemberLevelDetail.password) {
                  this.payPwd = "******";
                  this.dataForm.password = null;
                }
                this.dataForm.certificate = this.dataForm.certificate + '';
                this.dataForm.gender = this.dataForm.gender + '';
                this.dataForm.payType = parseInt(this.dataForm.payType);
                this.loadSellerLevel(this.dataForm.sellerId).then((levelList) => {
                  const level = levelList.find(l => l.id == this.dataForm.levelId);
                  this.dataForm.payAmount = level.payAmount;
                });
              }
            });
          }
        });
      },
      //加载平台商家数据
      remoteMethod(query) {
        this.loading = true;
        let that = this
        this.$http({
          url: this.$http.adornUrl("/hotel/hotelmember/platformMember"),
          method: "get",
          params: this.$http.adornParams({
            kw: query
          })
        }).then(({
          data
        }) => {
          this.loading = false;
          if (data && data.code === 0) {
            this.platfromMembers = data.data;
            that.platfromMembers.forEach((item, index) => {
              console.log(!item.tel + '手机号：' + item.tel)
              if (!item.tel) {
                that.platfromMembers.splice(index, 1)
              }
            })
          } else {
            this.$message.error(data.msg);
          }
        });
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs["dataForm"].validate(async valid => {
          this.dataForm.endTimeType = this.endTimeType;
          this.dataForm.payState = this.payState;
          this.dataForm.gender = this.gender;
          if (valid) {
            if (this.payInterfaceConfig.switchConfig == 1 && !this.dataForm.id) {
              if (this.payInterfaceConfig.payTypeId === this.dataForm.payType) {
                if (this.dataForm.payAmount <= 0) {
                  this.$message.error("扫码支付不可小于等于0");
                  return
                }
                this.payVisible = true;
                this.payTypeSign = type;
                this.changeFocus();
                return
              }
            }
            var childList = await this.documentTypelist.filter(child=>child.id == this.dataForm.certificate)
              var levelList = await this.levelList.filter(child=>child.id == this.dataForm.levelId)

            this.$http({
              url: this.$http.adornUrl(
                `/hotel/hotelmemberleveldetail/${
                !this.dataForm.id ? "save" : "update"
              }`
              ),
              method: "post",
              data: this.$http.adornData({
                id: this.dataForm.id || undefined,
                levelId: this.dataForm.levelId,
                memberId: this.dataForm.memberId,
                certificate: this.dataForm.certificate,
                certificateNo: this.dataForm.certificateNo,
                name: this.dataForm.name,
                accPeoId: this.dataForm.accPeoId,
                payState: this.dataForm.payState,
                mobile: this.dataForm.mobile,
                gender: this.dataForm.gender,
                payType: this.dataForm.payType,
                cardNo: this.dataForm.cardNo,
                endTime: this.dataForm.endTime,
                cardJustNo: this.dataForm.cardJustNo,
                cardInpNo: this.dataForm.cardInpNo,
                cardRealMoney: this.dataForm.payAmount,
                endTimeType: this.dataForm.endTimeType,
                address: this.dataForm.address,
                password: this.dataForm.password != "" ? this.dataForm.password : undefined,
                creator: this.dataForm.creator,
                createDate: this.dataForm.createDate,
                updateDate: this.dataForm.updateDate,
                sellerId: this.dataForm.sellerId,
                status: this.dataForm.status,
                salesman: this.dataForm.salesman,
                score: this.dataForm.score,
                balance: this.dataForm.balance,
                zjlxname:childList[0].label,
                djlx:levelList[0].name

              })
            }).then(({
              data
            }) => {
              if (data && data.code === 0) {
                this.$message({
                  message: "操作成功",
                  type: "success",
                  duration: 1500,
                  onClose: () => {
                    this.visible = false;
                    this.$emit("refreshDataList");
                  }
                });
              } else {
                this.$message.error(data.msg);
              }
            });
          }
        });
      },
      authClose() {
        // this.payVisible = false;
        this.payLoding = true;
        //扫码支付请求数据
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelsellerpayinterfaceconfig/preAuthBar'),
          method: 'post',
          data: this.$http.adornData({
            'type': 2, //正式
            'auth_no': this.auth_no, //授权码，客户的付款码
            'total_fee': this.dataForm.payAmount * 100, //金额，单位分
            'order_body': '会员卡办理', //订单描述
            'attach': '会员卡办理' //附加数据,原样返回
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            console.log(data)
            this.payVisible = false
            //保存入账信息
            this.auth_no = "";
            this.payLoding = false;
            var terminalTrace = data.data.terminalTrace
            this.authSubForm(terminalTrace);
          } else if (data.code == 3) {
            //循环查询订单，直至成功或失败
            this.timer = setInterval(() => {
              this.queryOrder(data.data);
            }, 1500);
          } else {
            this.payLoding = false;
            this.auth_no = "";
            this.payVisible = false
            this.$message.error(data.msg);
          }
        })
      },
      queryOrder(data) {
        this.$http({
          url: this.$http.adornUrl('/hotel/thotelsellerpayinterfaceconfig/commonQuery'),
          method: 'post',
          data: this.$http.adornData({
            'pay_type': data.payType,
            'terminal_trace': data.terminalTrace,
            'terminal_time': data.terminalTime,
            'out_trade_no': data.outTradeNo
          })
        }).then(({
          data
        }) => {
          console.log(data)
          if (data && data.code === 0) {
            clearInterval(this.timer)
            this.payLoding = false;
            console.log(data)
            this.payVisible = false
            this.auth_no = "";
            //保存入账信息
            var terminalTrace = data.data.terminalTrace
            this.authSubForm(terminalTrace);
          } else if (data.code === 3) {

          } else {
            clearInterval(this.timer)
            this.payLoding = false;
            this.payVisible = false
            this.auth_no = "";
            this.$message.error(data.msg);
          }
        })
      },
      authSubForm(terminalTrace) {
        this.$http({
          url: this.$http.adornUrl(
            `/hotel/hotelmemberleveldetail/${
            !this.dataForm.id ? "save" : "update"
          }`
          ),
          method: "post",
          data: this.$http.adornData({
            id: this.dataForm.id || undefined,

            levelId: this.dataForm.levelId,
            memberId: this.dataForm.memberId,
            collectionNo: terminalTrace,
            certificate: this.dataForm.certificate,
            certificateNo: this.dataForm.certificateNo,
            name: this.dataForm.name,
            accPeoId: this.dataForm.accPeoId,
            payState: this.dataForm.payState,
            mobile: this.dataForm.mobile,
            gender: this.dataForm.gender,
            payType: this.dataForm.payType,
            cardNo: this.dataForm.cardNo,
            endTime: this.dataForm.endTime,
            cardJustNo: this.dataForm.cardJustNo,
            cardInpNo: this.dataForm.cardInpNo,
            cardRealMoney: this.dataForm.payAmount,
            endTimeType: this.dataForm.endTimeType,
            address: this.dataForm.address,
            password: this.dataForm.password != "" ? this.dataForm.password : undefined,
            creator: this.dataForm.creator,
            createDate: this.dataForm.createDate,
            updateDate: this.dataForm.updateDate,
            sellerId: this.dataForm.sellerId,
            status: this.dataForm.status,
            salesman: this.dataForm.salesman,
            score: this.dataForm.score,
            balance: this.dataForm.balance
          })
        }).then(({
          data
        }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.visible = false;
                this.$emit("refreshDataList");
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      }
    }
  };
</script>
